package com.cy.pj.sys.service.impl;

import com.cy.pj.common.annotation.ClearCache;
import com.cy.pj.common.annotation.RequiredCache;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.Node;
import com.cy.pj.common.utils.AssertUtils;
import com.cy.pj.sys.dao.SysDeptDao;
import com.cy.pj.sys.dao.SysReasonDao;
import com.cy.pj.sys.pojo.SysDept;
import com.cy.pj.sys.pojo.SysReason;
import com.cy.pj.sys.service.SysDeptService;
import com.cy.pj.sys.service.SysReasonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service
public class SysReasonServiceImpl implements SysReasonService {
	@Autowired
	private SysReasonDao sysReasonDao;

	@RequiredCache
	@Override
	public List<Map<String, Object>> findObjects() {
		List<Map<String, Object>> list=
		sysReasonDao.findObjects();
		if(list==null||list.size()==0)
		throw new ServiceException("没有设置售后原因,请设置");
		return list;
	}
	@Override
	public List<Node> findZTreeNodes() {
		List<Node> list=
		sysReasonDao.findZTreeNodes();
		if(list==null||list.size()==0)
		throw new ServiceException("没有设置售后原因");
		return list;
	}

	@ClearCache
	@Override
	public int updateObject(SysReason sysReason) {
		//1.合法验证

		AssertUtils.isServiceValid(sysReason==null,"保存对象不能为空");
		AssertUtils.isServiceValid(StringUtils.isEmpty(sysReason.getName()), "售后原因不能为空");
		int rows;
		//2.更新数据
		try{
		rows=sysReasonDao.updateObject(sysReason);
		}catch(Exception e){
		e.printStackTrace();
		throw new ServiceException("更新失败");
		}
		//3.返回数据
		return rows;
	}
	
	@Override
	public int saveObject(SysReason sysReason) {
		//1.合法验证

		AssertUtils.isServiceValid(sysReason==null,"保存对象不能为空");
		AssertUtils.isServiceValid(StringUtils.isEmpty(sysReason.getName()), "售后原因不能为空");
		//2.保存数据
		int rows=sysReasonDao.insertObject(sysReason);

		//3.返回数据
		return rows;
	}
	@Override
	public int deleteObject(Integer id) {
		//1.合法性验证

		AssertUtils.isServiceValid(id==null||id<=0, "数据不合法,id="+id);
		//2.执行删除操作
		//2.1判定此id对应的菜单是否有子元素
		int childCount=sysReasonDao.getChildCount(id);

		AssertUtils.isServiceValid(childCount>0, "此元素有子元素，不允许删除");

		//2.3执行删除操作
		int rows=sysReasonDao.deleteObject(id);

		AssertUtils.isServiceValid(rows==0 ,"此条售后原因可能已经不存在");
		return rows;
	}


}
